package com.itheima.tanhua.admin.interceptor;

import com.itheima.commons.utils.JwtUtils;
import com.itheima.model.domain.Manager;
import com.itheima.model.domain.User;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterCeptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头
        String token = request.getHeader("Authorization");
        //2.使用工具类.判断token是否有效
        /*if(!JwtUtils.verifyToken(token)){
            response.setStatus(401);
            return false;
        }*/
        //有效先将用户信息放入到threadlocal中
        //判断是否带空格，去掉空格前面部分的
        System.out.println("请求路径" + request.getRequestURL() + "---" + "请求方法：" + request.getMethod());
        String[] s = token.split(" ");
        token = s[s.length - 1];
        System.out.println("请求路径" + request.getContextPath() + "---" + "请求方法：" + request.getMethod());
        if(s.length>1) {
            Claims claims = JwtUtils.getClaims(token);
            Manager manager = new Manager();
            manager.setUid(Long.valueOf((Integer) claims.get("uid")));
            manager.setUsername((String) claims.get("username"));
            ManagerHolder.set(manager);
        }else {
            Claims claims = JwtUtils.getClaims(token);
            User user = new User();
            user.setId(Long.valueOf((Integer) claims.get("id")));
            user.setMobile((String) claims.get("username"));
            UserHolder.set(user);
        }
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }

}
